﻿from flask import Flask, g, render_template, request,flash,redirect,url_for,Blueprint
import pymysql,json,datetime,json
from .login.login import *
from .setting import *

from flask_cors import CORS
role_blue = Blueprint('role',__name__)


def json_encoder(obj):
    if isinstance(obj, datetime.datetime):
        return obj.strftime("%Y-%m-%d %X")
    elif isinstance(obj, datetime.date):
        return obj.strftime("%Y-%m-%d")
@role_blue.route('/sys/role/list')
# @login_required
def rolelist():
	if request.args.get('roleName'):like = request.args.get('roleName')
	else:like=''
	if request.args.get('page'):page = request.args.get('page')
	else:page=1
	if request.args.get('limit'):limit = request.args.get('limit')
	else:limit=10
	# print(like,page,limit)
	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql = "SELECT * from sys_role WHERE  role_name LIKE '%"+like+"%'  LIMIT "+str(limit) +" OFFSET " +str((int(page)-1)*int(limit))
	sqlcount = "SELECT count(*) from sys_role  WHERE  role_name LIKE '%"+like+"%'"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		dataList1 = cursor.fetchall()
		# for row in dataList:
			# print(row)
		dataList=[]
		for i in range(len(dataList1)):
			dataList.append({'roleId':dataList1[i][0],'roleName':dataList1[i][1],'remark':dataList1[i][2],'createUserId':dataList1[i][3],'createTime':dataList1[i][4]})
		cursor.execute(sqlcount)
		count = cursor.fetchall()[0][0]
	except Exception as e:
		return "Error: unable to fetch data from sys_role"+str(e)
	db.close()
	data={
			'msg': 'success',
			'code': 0,
			'page': {
				'totalCount': len(dataList),
				'pageSize': 10,
				'totalPage': 1,
				'currPage': 1,
				'list': dataList
				}
			}
	return json.dumps(data,default=json_encoder)
@role_blue.route('/sys/role/save',methods=['POST'])
# @login_required
def rolesave():
	if request.data:
		if printrequestdata:print(request.data)
		d=json.loads(str(request.data, 'UTF-8'))
		if 'roleName' in d.keys():roleName = d['roleName']
		else:roleName=''
		if 'remark' in d.keys():remark = d['remark']
		else:remark=''
		if 'createUserId' in d.keys():createUserId = d['createUserId']
		else:createUserId=''
		if 'createTime' in d.keys():createTime = d['createTime']
		else:createTime=''
	elif request.form:
		roleName = request.form['roleName']
		remark = request.form['remark']
		createUserId = request.form['createUserId']
		createTime = request.form['createTime']

	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql = 'insert into sys_role (role_name,remark,create_user_id,create_time) values('+"'"+str(roleName)+"',"+"'"+str(remark)+"',"+"'"+str(createUserId)+"',"+"'"+str(createTime)+"')"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		db.commit()
	except Exception as e:
		db.rollback()
		return "Error: unable to save data from sys_role"+str(e)
	db.close()
	
	data={
      'msg': 'success',
      'code': 0
    }
	return json.dumps(data,default=json_encoder)
@role_blue.route('/sys/role/update',methods=['POST'])
# @login_required
def roleupdate():
	if request.data:
		if printrequestdata:print(request.data)
		d=json.loads(str(request.data, 'UTF-8'))
		if 'roleId' in d.keys():roleId = d['roleId']
		else:roleId=''
		if 'roleName' in d.keys():roleName = d['roleName']
		else:roleName=''
		if 'remark' in d.keys():remark = d['remark']
		else:remark=''
		if 'createUserId' in d.keys():createUserId = d['createUserId']
		else:createUserId=''
		if 'createTime' in d.keys():createTime = d['createTime']
		else:createTime=''
	elif request.form:
		roleId = request.form['roleId']
		roleName = request.form['roleName']
		remark = request.form['remark']
		createUserId = request.form['createUserId']
		createTime = request.form['createTime']

	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	cursor = db.cursor()
	sql ="UPDATE sys_role SET role_name='"+str(roleName)+"',remark='"+str(remark)+"',create_user_id='"+str(createUserId)+"',create_time='"+str(createTime)+"'"+ "WHERE role_id = '"+str(roleId)+"'"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		db.commit()
	except Exception as e:
		db.rollback()
		return "Error: unable to delete data from sys_role"+str(e)
	db.close()

	data={
	  'msg': 'success',
	  'code': 0
	}
	return json.dumps(data,default=json_encoder)
@role_blue.route('/sys/role/delete',methods=['POST'])
# @login_required
def roledelete():
	# print("content_type:", request.headers.get("content_type"))
	# print("data:", request.data)
	# print("data:", str(request.data, 'UTF-8'))
	# print("form:", request.form)
	# print("files:", request.files)
	if request.data:
		if printrequestdata:print(request.data)
		d=json.loads(str(request.data, 'UTF-8'))
		if 'roleId' in d.keys():roleId = d['roleId']
		else:roleId=''
	elif request.form:
		roleId = request.form['roleId']

	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql ="DELETE FROM sys_role WHERE role_id='"+str(roleId)+"'"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		db.commit()
	except Exception as e:
		db.rollback()
		return "Error: unable to delete data from sys_role"+str(e)
	db.close()

	data={
	  'msg': 'success',
	  'code': 0
	}
	return json.dumps(data,default=json_encoder)
@role_blue.route('/sys/role/info')
@role_blue.route('/sys/role/info/<id>')
# @login_required
def roleinfo(id=None):
	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql ="SELECT * from sys_role where  role_id='"+str(id)+"'"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		dataList1 = cursor.fetchall()
		# for row in dataList:
			# print(row)
		role={'roleId':dataList1[0][0],'roleName':dataList1[0][1],'remark':dataList1[0][2],'createUserId':dataList1[0][3],'createTime':dataList1[0][4]}
		data={
				'msg': 'success',
				'code': 0,
				'role': role
				}
		return json.dumps(data,default=json_encoder)
	except Exception as e:
		return "Error: unable to fetch data from sys_role"+str(e)
	db.close()
@role_blue.route('/sys/role/select')
# @login_required
def roleselect():
	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql = "SELECT * from sys_role"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		dataList1 = cursor.fetchall()
		# for row in dataList1:
			# print(row)
		dataList=[]
		for i in range(len(dataList1)):
			dataList.append({'roleId':dataList1[i][0],'roleName':dataList1[i][1],'remark':dataList1[i][2],'createUserId':dataList1[i][3],'createTime':dataList1[i][4]})
		# print(dataList)
		data={
				'msg': 'success',
				'code': 0,
				'list': dataList
				}
		return json.dumps(data,default=json_encoder)
	except Exception as e:
		return "Error: unable to fetch data from sys_role"+str(e)
	db.close()	
	
	
	


